package com.dzf.controller;

import com.dzf.entity.*;
import com.dzf.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@CrossOrigin
@RestController
@RequestMapping("/api/public")
public class PublicController {
    @Autowired
    BookService bookService;
    @Autowired
    HotService hotService;
    @Autowired
    LargeFileService largeFileService;
    @Autowired
    BookTypeService bookTypeService;
    @Autowired
    UserService userService;

    @RequestMapping("/type/findAll2")
    public RespJson findAll2(){
        List<Type> list = bookTypeService.findAll2();
        return RespJson.pack(200,"ok",list);
    }

    @RequestMapping("/findHot/{num}/{type}")
    public RespJson findHot(@PathVariable("num")int num,@PathVariable("type")int type){
        Map<String, Object> map = new HashMap<>();
        map.put("num",num);
        map.put("type",type);
        List<Hot> hots = hotService.findHot(map);
        return RespJson.pack(200,"ok",hots);
    }



    @RequestMapping("/book/findIf/{start}/{num}")
    public RespJson findIf(@PathVariable("start")int start,
                           @PathVariable("num")int num,
                           @RequestBody String condition){
        System.err.println("++++++++++++++++++++++++++++++++"+condition);
        Map<String, Object> map = new HashMap<>();
        map.put("condition",condition);

        int total = bookService.findByTotal(map);
        List<Book> books = bookService.findByIf(start, num, condition);
        System.out.println(books);
        Map<Object, Object> result = new HashMap<>();
        result.put("total",total);
        result.put("books",books);
        return RespJson.pack(200,"",result);
    }

    @RequestMapping("/findBookByPage/{start}/{num}/{typeid}")
    public RespJson findBookByPage(@PathVariable("start")int start,
                                   @PathVariable("num")int num,
                                   @PathVariable("typeid")int typeid){



        Map<String, Object> books = bookService.findBookByPage(start, num, typeid);


        return RespJson.pack(200,"",books);
    }

    @RequestMapping("/showImg/{id}")
    public void showImg(@PathVariable("id")String id,
                            HttpServletResponse response)
    {
        LargeFile largeFile = largeFileService.findByPic(id);
        if (largeFile==null)return;//对象为空则结束方法
        try {
            response.setContentType("image/jpeg");//将图片以jpg形式返回
            response.getOutputStream().write((byte[]) largeFile.getContent());//获取response的输出流，写出图片的内容
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/type/findAll")
    public RespJson findAll()
    {
        List<BookType> bookTypes = bookTypeService.findAll();
        return RespJson.pack(200,"",bookTypes);
    }

    @RequestMapping("/book/addRate/{bookid}")
    public RespJson addRate(@PathVariable("bookid")int bookid)
    {
        try {
            bookService.addRate(bookid);
        }catch (Exception e)
        {
            e.printStackTrace();
            return RespJson.pack(100,"未登录，失败",null);
        }
        return RespJson.pack(200,"点赞成功！",null);
    }

    @RequestMapping("findBookByPageSale/{start}/{num}/{typeid}")
    public RespJson findBookByPageSale(@PathVariable("start")int start,
                                   @PathVariable("num")int num,
                                   @PathVariable("typeid")int typeid){
        Map<String, Object> map = new HashMap<>();
        map.put("typeid",typeid);
        map.put("condition","salenum");

        //将已经打包完成的数据返回
        Map<String, Object> map1 = bookService.findBookByPageOrd(start, num, map);
        return RespJson.pack(200,"",map1);
    }


    @RequestMapping("/findBookByPageRate/{start}/{num}/{typeid}")
    public RespJson findBookByPageRate(@PathVariable("start")int start,
                                   @PathVariable("num")int num,
                                   @PathVariable("typeid")int typeid){
        Map<String, Object> map = new HashMap<>();
        map.put("typeid",typeid);
        map.put("condition","rate");

        //将已经打包完成的数据返回
        Map<String, Object> map1 = bookService.findBookByPageOrd(start, num, map);
        return RespJson.pack(200,"",map1);
    }


    @RequestMapping("/findBookByPageFav/{start}/{num}/{typeid}")
    public RespJson findBookByPageFav(@PathVariable("start")int start,
                                   @PathVariable("num")int num,
                                   @PathVariable("typeid")int typeid){
        Map<String, Object> map = new HashMap<>();
        map.put("typeid",typeid);
        map.put("condition","favnum");

        //将已经打包完成的数据返回
        Map<String, Object> map1 = bookService.findBookByPageOrd(start, num, map);
        return RespJson.pack(200,"",map1);
    }

    @RequestMapping("/book/findRate5")
    public RespJson findRate5()
    {
        List<Book> books = bookService.findRate5();
        return RespJson.pack(200,"OK",books);
    }
    @RequestMapping("/book/findSale5")
    public RespJson findSale5()
    {
        List<Book> books = bookService.findSale5();
        return RespJson.pack(200,"OK",books);
    }
    @RequestMapping("/book/findFav5")
    public RespJson findFav5()
    {
        List<Book> books = bookService.findFav5();
        return RespJson.pack(200,"OK",books);
    }

    @RequestMapping("/user/addUser")
    public RespJson addUser(User user,@RequestParam("pic") MultipartFile pic){
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        user.setPassword(bc.encode(user.getPassword()));
        UUID uuid = UUID.randomUUID();
        LargeFile largeFile = new LargeFile();
        try {
            if (pic!=null&&pic.getSize()>0)
            {
                largeFile.setId(uuid.toString().replace("-",""));
                largeFile.setFilename(pic.getOriginalFilename());
                largeFile.setContent(pic.getBytes());
                largeFileService.addLargeFile(largeFile);//文件内容
            }

            if (largeFile.getId()!=null ||!" ".equals(largeFile.getId()))
            {
                user.setImg(uuid.toString().replace("-",""));
            }
            userService.addUser(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return RespJson.pack(200,"ok",null);
    }


    @GetMapping("/info/all")
    public Authentication getauthentication(Authentication authentication)
    {
        return authentication;
    }

    @GetMapping("/info/getUser")
    public Object getUser(){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.err.println("principal="+principal);
        if (principal==null)return null;
        if (principal instanceof UserDetails) {

            return (UserDetails)principal;
        }else
        {
            System.err.println("1");
            return String.valueOf(principal);
        }
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }
}
